package com.taobao.ad.hadoop.main;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path; 
import com.taobao.ad.hadoop.common.JobNode;
import com.taobao.ad.hadoop.common.XmlParse;
import com.taobao.ad.hadoop.utility.DateUtil;

public class Main {
	public static void main(String[] args) throws Exception {
		if (args.length < 4) {
			System.out.println("Usage: xmlconf input output intermediate jobindex");
			return;
		}
		String xmlconf = args[0];
		String input = args[1];
		String output = args[2];
		String intermediate = args[3];
		int jobindex = 1;
		if (args.length == 5) {
			jobindex = Integer.parseInt(args[4]);
		}
		List<Map<String, String>> jobconfList = XmlParse.parse(xmlconf);
		List<JobNode> jobNodeList = InitJob.GenerageJobPlan(jobconfList, input,
				output, intermediate);
		int sumTime = 0;
		Date StartTime = new Date();
		for (JobNode jobnode : jobNodeList) {
			Date start = new Date(); 
			if(!jobnode.runJob(jobindex)){ 
				return;
			}
			Date end = new Date();
			int seconds = DateUtil.GetSecondsSpan(start, end);
			sumTime += seconds;
			int hours = seconds / 3600;
			int minutes = (seconds - hours * 3600) / 60;
			seconds = seconds % 60;
			System.out.println("\nJob Start Time:"
					+ DateUtil.GetDateTimeString(start, "yyyy-MM-dd HH:mm:ss"));
			System.out.println("Job End Time:  "
					+ DateUtil.GetDateTimeString(end, "yyyy-MM-dd HH:mm:ss"));
			System.out.println("Job Time Use:" + hours + "hour  " + minutes
					+ "minutes  " + seconds + "seconds");
		}
		Date EndTime = new Date();
		FileSystem hdfs = FileSystem.get(new Configuration());
		System.out.println("\nDeleting intermediate path:" + intermediate);
		hdfs.delete(new Path(intermediate), true);
		int seconds = sumTime;
		int hours = seconds / 3600;
		int minutes = (seconds - hours * 3600) / 60;
		seconds = seconds % 60;
		System.out.println("\nAll Jobs Start Time:"
				+ DateUtil.GetDateTimeString(StartTime, "yyyy-MM-dd HH:mm:ss"));
		System.out.println("All Jobs End Time:  "
				+ DateUtil.GetDateTimeString(EndTime, "yyyy-MM-dd HH:mm:ss"));
		System.out.println("All Jobs Time Use:" + hours + "hour  " + minutes
				+ "minutes  " + seconds + "seconds");
		System.out.println("\nAll Jobs Finished!\n");
		System.out.println("\nOutput Path:" + output + "\n\n");
	}
}